package com.example.demo.Service;

import com.example.demo.Entity.Item;
import com.example.demo.Entity.Like;
import com.example.demo.Entity.User;
import com.example.demo.Repository.LikeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LikeService {

    @Autowired
    private LikeRepository likeRepository;

    public void addLike(Long itemId, Long userId) {
        Like like = new Like();
        like.setItem(new Item(itemId));
        like.setUser(new User(userId));
        like.setLikedAt(LocalDateTime.now());
        likeRepository.save(like);
    }

    public void removeLike(Long itemId, Long userId) {
        likeRepository.deleteByItemIdAndUserId(itemId, userId);
    }
    public int getLikeCount(Long itemId) {
        return likeRepository.countByItemId(itemId);
    }

    public boolean existsByItemIdAndUserId(Long itemId, Long userId) {
        return likeRepository.existsByItemIdAndUserId(itemId, userId);
    }
    public Map<Long, Integer> getBatchLikeCounts(List<Long> itemIds) {
        List<Like> likes = likeRepository.findByItemIdIn(itemIds);

        Map<Long, Integer> countsMap = new HashMap<>();
        for (Long itemId : itemIds) {
            countsMap.put(itemId, 0);
        }

        for (Like like : likes) {
            Long itemId = like.getItem().getId();
            if (countsMap.containsKey(itemId)) {
                countsMap.put(itemId, countsMap.get(itemId) + 1);
            }
        }

        return countsMap;
    }
}
